package com.shop.filter;

import com.shop.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 鉴权过滤器，判断tomcat的session中是否有用户对象信息如果有就放行
 * @author
 */
public class PermFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取用户的访问路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uriStr=request.getRequestURI();
        //判断用户路径，放行所有静态资源，放行用户登录的路径，首页，和商品查询等路径
        if(uriStr.endsWith("login.jsp")||uriStr.endsWith("/code")
                || uriStr.endsWith(".js")|| uriStr.endsWith(".css")
                || uriStr.endsWith(".jpg")|| uriStr.endsWith(".png")
                || uriStr.endsWith(".gif")|| uriStr.endsWith(".eot")
                || uriStr.endsWith(".svg")|| uriStr.endsWith(".ttf")
                || uriStr.endsWith(".woff")|| uriStr.endsWith(".woff2")){
            filterChain.doFilter(servletRequest,servletResponse);
            return ;
        }

        //获取会话的session对象
        HttpSession session = request.getSession();
//        获取对象信息
        User user =(User) session.getAttribute("admin");
        if(user != null){
            //有用户信息就放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //没有重定向到登陆页面
            response.sendRedirect("/admin/login.jsp");
        }


    }

    @Override
    public void destroy() {

    }
}
